﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using TSites.Core.Domain.UserMangerment;
using System.Collections.Generic;
using TSites.Administrator.Validation;

namespace TSites.Administrator.Models
{
	public class UserEditViewModel
	{
		[Required]
		[StringLength(20, MinimumLength = 6)]
		[RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
		[ScaffoldColumn(true)]
		public string UserId { get; set; }

		[StringLength(1024, MinimumLength = 6)]
		public string Password { get; set; }

		[Required]
		public string Username { get; set; }

		[DateRangeAttribute()]
		[DataType(DataType.Date)]
		[DisplayFormat(DataFormatString="dd/MM/yyyy")]
		public DateTime DateOfBirth { get; set; }

		[Required]
		public char Sex { get; set; }

		[Required]
		[Remote("IsEmail4EditAvailable", "UserManagement", AdditionalFields = "UserId")]
		[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})\s*")]
		public string Email { get; set; }

		public string Address { get; set; }
		public string PhoneNumber { get; set; }

		public User Convert2User()
		{
			var addresses = new List<Address>();
			addresses.Add(new Address()
			{
				UserAddress = Address
			});

			var phones = new List<Phone>();
			phones.Add(new Phone()
			{
				PhoneNumber = PhoneNumber
			});

			User currentUser = new User()
			{
				ID = UserId,
				UserName = Username,
				Password = Password,
				Sex = Sex.ToString(),
				Email = Email,
				Addresses = addresses,
				Phones = phones
			};

			if (DateOfBirth != DateTime.MinValue)
			{
				currentUser.DateOfBirth = DateOfBirth;
			}

			return currentUser;
		}
	}
}